#include "proc.h"
#include "common.h"

#define MAX_NR_PROC 4

static PCB pcb[MAX_NR_PROC];
static int nr_proc = 0;
PCB *current = NULL;
static int num = 0;
extern int current_game;

uintptr_t loader(_Protect *as, const char *filename);

void load_prog(const char *filename) {
  int i = nr_proc ++;
  _protect(&pcb[i].as);

  uintptr_t entry = loader(&pcb[i].as, filename);

  // TODO: remove the following three lines after you have implemented _umake()
  // _switch(&pcb[i].as);
  // current = &pcb[i];
  // ((void (*)(void))entry)();

  _Area stack;
  stack.start = pcb[i].stack;
  stack.end = stack.start + sizeof(pcb[i].stack);

  pcb[i].tf = _umake(&pcb[i].as, stack, stack, (void *)entry, NULL, NULL);
}

_RegSet* schedule(_RegSet *prev) {
  current->tf = prev;
  if (current_game == 0) {
    // 仙剑奇侠传和 hello 程序分时运行
    current = &pcb[0];
    if (num != 500)
      num++;
    else {
      current = &pcb[1];
      num = 0;
    }
  }
  else
  {
    current = &pcb[2];
  }
  
  // current = &pcb[current_game];
  // if(num != 500)
  //   num++;
  // else
  // {
  //   current = &pcb[current_game];
  //   num = 0;
  // }
  _switch(&current->as); //要切换到新进程的虚拟地址空间
  return current->tf;
}
